var pageData = {
    sha: '',
    list: [],
    isFocus: false // 是否获取焦点
}

// 验证登录状态
function verifyLoginState() {
    var textDom = document.getElementById("text-value")
    // var inputVal = textDom.value.replace(/\s/g, ""); 
    // var token = Local.get('token') || inputVal || getUrlVariable("token") || ''
    var queryParams = new URLSearchParams(window.location.search);  
    var token = queryParams.get('token');
    var sendBtn = document.getElementById("send-btn")
    var loginBtn = document.getElementById("login-btn")
    textDom.value = ''
    console.log("获取token", token);
    sendBtn.style.display = 'none'
    loginBtn.style.display = 'inline'
    token && login(token, function (res) {
        console.log('登录结果', res);
        if (res.succeed) {
            sendBtn.style.display = 'inline'
            loginBtn.style.display = 'none'
            getData()
        }
    })
}
// 登录
function login(token, callback) {
    if (!token) return
    // 获取授权用户的全部邮箱；用于验证token是否合法
    var request = new XMLHttpRequest();
    request.open(
        'GET',
        `https://gitee.com/api/v5/emails?access_token=${token}`,
        true
    );
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
            if (!request) return
            var res = JSON.parse(request.responseText);
            // console.log('token有效', res);
            Local.set('token', token)
            callback({
                succeed: true,
                message: '登录成功',
            })
        } else if (request.readyState === 4 && request.status === 401) {
            var res = JSON.parse(request.response)
            // console.log("token错误", request);
            Local.remove('token')
            callback({
                succeed: false,
                message: res.message,
            })
        }
    };
    request.send();
}
// 引入数据
function getData() {
    var params = {
        access_token: Local.get('token'),
        owner: 'konghaowei',
        repo: 'gitee-database',
        path: 'database/leave-message.json',
        ref: 'other',
    }
    var request = new XMLHttpRequest();
    request.open(
        'GET',
        `https://gitee.com/api/v5/repos/${params.owner}/${params.repo}/contents/${params.path}?access_token=${params.access_token}&ref=${params.ref}`,
        true
    );
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
            if (!request) return
            var res = JSON.parse(request.responseText);
            console.log('数据', res);
            var data = jsonToBase64('decode', res.content)
            data = JSON.parse(data)
            pageData.list = data.list
            pageData.sha = res.sha
            console.log("最终", {
                data,
                pageData
            });
            render()
        }
    };
    request.send();
}
// 消息 item 模板
function itemTemplate(item) {
    return `
        <div class="item" id="item-${item.id}">
            <div class="copy-box">${item.text}</div>
            <button class="del-btn" data-id="${item.id}">删除</button>
        </div>
    `
}
// 渲染
function render() {
    // 测试代码
    // pageData.list = []
    // for (let i = 0; i < 50; i++) {
    //     var id = createRandomId()
    //     pageData.list.push({ id: id, text: '文本-' + id, })
    // }
    var itemHTML = ''
    for (const item of pageData.list) {
        itemHTML += itemTemplate(item)
    }
    var DOM = document.getElementById("list-box");
    DOM.innerHTML = itemHTML;
    scrollHeight()
}
// 复制事件
function copyFun(e) {
    var dom = e.target
    copyText(dom.innerText, function (text) {
        console.log('复制成功回调：' + text);
    });
}
// 删除事件
function delFun(e) {
    var id = e.target.dataset.id
    for (let i = 0; i < pageData.list.length; i++) {
        const item = pageData.list[i];
        if (item.id === id) {
            pageData.list.splice(i, 1)
            break
        }
    }
    var DOM = document.getElementById("item-" + id)
    if (DOM) DOM.remove();
    console.log("pageData", pageData);
    update()
}
// 创建 item
function createItem() {
    var id = createRandomId()
    var textDom = document.getElementById("text-value")
    if (!textDom.value) return
    var item = { id: id, text: textDom.value }
    pageData.list.push(item)
    var DOM = document.getElementById("list-box");
    DOM.insertAdjacentHTML("beforeEnd", itemTemplate(item));
    textDom.value = ''
    update()
    scrollHeight()
}
// 更新数据
function update() {
    var data = {
        "remark": "留言项目的数据",
        "list": pageData.list
    }
    var content = jsonToBase64('encode', JSON.stringify(data, undefined, 2)) // 编码
    // console.log("更新数据", {
    //     '0-pageData': pageData,
    //     '1-content': content,
    //     '2-sha': pageData.sha
    // });
    submitData(content, pageData.sha, function (res) {
        pageData.sha = res.content.sha
    })
}
function scrollHeight() {
    var Dom = document.getElementById('list-box');
    Dom.scrollTop = Dom.scrollHeight;
}
// 设置事件
function setEvent() {
    var appDOM = document.getElementById("app");
    appDOM.addEventListener("click", function (e) {
        if (e.target.className.indexOf("copy-box") >= 0) copyFun(e)
        if (e.target.className.indexOf("del-btn") >= 0) delFun(e)
        if (e.target.id === 'login-btn') verifyLoginState()
        if (e.target.id === 'send-btn') createItem()
    });
    document.addEventListener('keyup', (e) => {
        var token = Local.get('token')
        if (/Enter/i.test(e.key)) {
            if (!token) {
                verifyLoginState()
            } else if (pageData.isFocus) {
                createItem()
            }
        }
    })
    document.getElementById('text-value').onfocus = function () {
        pageData.isFocus = true
    }
    document.getElementById('text-value').onblur = function () {
        pageData.isFocus = false
    }
}
// 初始化
function init() {
    setEvent()
    verifyLoginState()
}

init()